package com.esproject.esutils;

import com.esproject.Annonation.ESIndexField;
import com.esproject.bean.CvInfo;
import com.google.common.collect.Maps;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * 通用注解解析成字段与值的Map
 * <p/>
 * Created by yan_li on 2017/2/19.
 */
public class AnnonResolverFieldValue {

    private Class clazz;

    private Object obj;

    private Class<? extends Annotation> annotationClass;

    private AnnonResolverFieldValue(ResolverBuilder resolver) {
        this.clazz = resolver.clazz;
        this.obj = resolver.obj;
        this.annotationClass = resolver.annotationClass;
    }

    public static ResolverBuilder buider() {
        return new AnnonResolverFieldValue.ResolverBuilder();
    }

    public static class ResolverBuilder {
        private Class clazz;

        private Object obj;

        private Class<? extends Annotation> annotationClass;

        public ResolverBuilder clazz(Class clazz) {
            this.clazz = clazz;
            return this;
        }

        public ResolverBuilder instanceObj(Object obj) {
            this.obj = obj;
            return this;
        }

        public ResolverBuilder annotation(Class<? extends Annotation> annotationClass) {
            this.annotationClass = annotationClass;
            return this;
        }

        public AnnonResolverFieldValue build() {
            return new AnnonResolverFieldValue(this);
        }
    }

    public Map<String, Object> ResolverFieldValue() {
        try {
            Class clazz = this.clazz;
            Class<? extends Annotation> annotationClass = this.annotationClass;
            Field[] declaredFields = clazz.getDeclaredFields();
            Map<String, Object> fieldValues = Maps.newHashMap();
            for (Field f : declaredFields) {
                f.setAccessible(true);
                if (f.isAnnotationPresent(annotationClass)) {
                    Object o = f.get(this.obj);
                    ESIndexField esIndex = f.getAnnotation(ESIndexField.class);
                    boolean idFlag = esIndex.id();
                    if(idFlag){
                        fieldValues.put("_es_id", f.get(this.obj));
                    }
                    if (o != null) {
                        fieldValues.put(f.getName(), f.get(this.obj));
                    }
                }
            }
            return fieldValues;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        CvInfo cv = new CvInfo();
        cv.setCuid("22");
        cv.setCvid("222AF");
        cv.setMonths("1年12个月");
        Map<String, Object> stringObjectMap = AnnonResolverFieldValue.buider().clazz(CvInfo.class).instanceObj(cv).annotation(ESIndexField.class).build().ResolverFieldValue();
        System.out.println(stringObjectMap);
    }
}
